package com.yc.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class QQ {
	// 套接字对象
	Socket socket;
	String name;
	
	public QQ(String name) {
		super();
		this.name = name;
	}

	public void createServer() throws IOException {
		// 创建连接服务器对象
		ServerSocket server = new ServerSocket(8888);
		System.out.println("监听端口:8888");
		// 监听客户端连接请求
		socket = server.accept();  // IO操作 => 线程阻塞
		System.out.println("接收到客户端连接请求, 连接成功!");
	}

	public void connect() throws UnknownHostException, IOException {
		socket = new Socket("127.0.0.1",8888);
		System.out.println("连接服務器成功!");
	}
	
	public void read() throws IOException {
		String msg;
		InputStream in = socket.getInputStream();
		byte[] bytes = new byte[1024];
		while(true) {
			int count = in.read(bytes);
			msg = new String(bytes,0,count);
			System.out.println(msg);
		}
	}
	
	public void write() throws IOException {
		OutputStream out = socket.getOutputStream();
		Scanner sc = new Scanner(System.in);
		String msg;
		while(true) {
			System.out.print("请输入:");
			msg = name + ":" + sc.nextLine();
			out.write(msg.getBytes());
		}
	}
	
	///////////////////////// SWT ///////////////////////////////
	public void write(String msg) throws IOException {
		OutputStream out = socket.getOutputStream();
		msg = name + ":" + msg;
		out.write(msg.getBytes());
	}
	
	//  Consumer 消费者函数接口
	public void read(java.util.function.Consumer<String> consumer) throws IOException {
		String msg;
		InputStream in = socket.getInputStream();
		byte[] bytes = new byte[1024];
		while(true) {
			int count = in.read(bytes);
			msg = new String(bytes,0,count);
			// 输出图形界面
			consumer.accept(msg);
		}
	}
	
	
	
	
}
